import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
// 添加请求拦截器
service.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么
    const token = store.state.user.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// response interceptor
// 添加响应拦截器
service.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    console.log(response, '响应正常')
    if (!response.data.success) {
      // 手动抛错
      return Promise.reject(new Error(response.data.message))
    }
    return response
  },
  async function(error) {
    // 对响应错误做点什么
    console.log(error.response, '响应错误')
    if (!error.response.data.success) {
      await store.dispatch('user/logout')
      // .vue -- this.$route.fullPath
      //  .js -- router.currentRoute.fullPath

      router.push(`/login?url=${encodeURIComponent(router.currentRoute.fullPath)}`)
      return Promise.reject(new Error(error.response.data.message))
    }
    return Promise.reject(error)
  }
)

export default service
